import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRemoteModeOptionsStore } from './remoteModeOptions'
import { useReplayModeOptionsStore } from './replayModeOptions'
import { useLanguageStore } from './language'
import { appoxEnums } from '@/appox/appox'
import { agencyAsync } from '@/appox/appox'
import { appoxUtility } from '@/appox/appox'

export const useControllerStore = defineStore('controller', () => {
  // 状态
  const appStatus = ref(appoxEnums.ApplicationStatus.Idle)
  const appMode = ref(appoxEnums.ApplicationMode.Online)
  const dataPath = ref('---')
  const isConfigDataPathAvailable = ref(false)
  const isFileOutputEnabled = ref(false)
  const isSwitchSessionAvailable = ref(false)
  
  // 缓冲区信息
  const bufferBegin = ref(0)
  const bufferEnd = ref(0)
  const interestTime = ref(0)
  
  // 回放速度信息
  const targetReplaySpeed = ref(0)
  const actualReplaySpeed = ref(0)

  // 防抖变量
  let updating = false
  
  let lastSwitchAppModeTime = null
  let lastSetTargetInterestTime = null
  let lastSetTargetReplaySpeedTime = null
  
  // 计算属性
  const isIdle = computed(() => appStatus.value === appoxEnums.ApplicationStatus.Idle)
  const isRunning = computed(() => appStatus.value === appoxEnums.ApplicationStatus.Running)
  const isDataPathValid = computed(() => dataPath.value !== '---' && dataPath.value !== 'na')
  const isDataSettingsConfigurable = computed(() => 
    appMode.value === appoxEnums.ApplicationMode.Replay || 
    appMode.value === appoxEnums.ApplicationMode.Offline
  )
  const isOnlineMode = computed(() => appMode.value === appoxEnums.ApplicationMode.Online)
  const isRemoteMode = computed(() => appMode.value === appoxEnums.ApplicationMode.Remote)
  const isOfflineMode = computed(() => appMode.value === appoxEnums.ApplicationMode.Offline)
  const isReplayMode = computed(() => appMode.value === appoxEnums.ApplicationMode.Replay)
  
  // 新增计算属性
  const canAccessSessionList = computed(() => 
    isIdle.value && 
    isDataPathValid.value && 
    isDataSettingsConfigurable.value
  )
  
  const canSelectDataPath = computed(() => 
    isIdle.value && 
    isConfigDataPathAvailable.value
  )
  
  const canAccessGenerationSetting = computed(() => 
    isIdle.value && 
    isDataPathValid.value && 
    isDataSettingsConfigurable.value
  )
  
  const canRecord = computed(() => 
    (isIdle.value && appMode.value !== appoxEnums.ApplicationMode.Unknown && appMode.value !== appoxEnums.ApplicationMode.Replay) ||
    isSwitchSessionAvailable.value
  )
  
  const canPreview = computed(() => 
    (isIdle.value && appMode.value !== appoxEnums.ApplicationMode.Unknown) ||
    (isSwitchSessionAvailable.value && isFileOutputEnabled.value)
  )
  
  const previewButtonType = computed(() => 
    isRunning.value && !isFileOutputEnabled.value ? 'warning' : 'primary'
  )
  
  const recordButtonType = computed(() => 
    isRunning.value && isFileOutputEnabled.value ? 'warning' : 'primary'
  )
  
  const stopButtonType = computed(() => 
    isIdle.value ? 'warning' : 'primary'
  )
  
  const showReplaySpeed = computed(() => 
    appMode.value === appoxEnums.ApplicationMode.Replay || 
    appMode.value === appoxEnums.ApplicationMode.Offline
  )
  
  const formatReplaySpeed = computed(() => {
    const target = targetReplaySpeed.value.toFixed(1)
    const actual = actualReplaySpeed.value.toFixed(1)
    const languageStore = useLanguageStore()
    return languageStore.isChinese ? `(目标${target}x, 当前${actual}x)` : `(Target ${target}x, Actual ${actual}x)`
  })
  
  // 动作
  async function switchToOnlineMode() {
    lastSwitchAppModeTime = Date.now()
    appMode.value = appoxEnums.ApplicationMode.Online
    await agencyAsync.switchAppMode('default', appoxEnums.ApplicationMode.Online, 3)
  }

  async function switchToRemoteMode() {
    lastSwitchAppModeTime = Date.now()
    appMode.value = appoxEnums.ApplicationMode.Remote
    await agencyAsync.switchAppMode('default', appoxEnums.ApplicationMode.Remote, 3)
  }

  async function switchToOfflineMode() {
    lastSwitchAppModeTime = Date.now()
    appMode.value = appoxEnums.ApplicationMode.Offline
    await agencyAsync.switchAppMode('default', appoxEnums.ApplicationMode.Offline, 3)
  }

  async function switchToReplayMode() {
    lastSwitchAppModeTime = Date.now()
    appMode.value = appoxEnums.ApplicationMode.Replay
    await agencyAsync.switchAppMode('default', appoxEnums.ApplicationMode.Replay, 3)
  }
  
  async function startPreview() {
    switch (appMode.value) {
      case appoxEnums.ApplicationMode.Online:
        await agencyAsync.startOnline(false, true, null)
        break
      case appoxEnums.ApplicationMode.Offline:
        await agencyAsync.startOffline(false, true, null)
        break
      case appoxEnums.ApplicationMode.Replay:
        const replayModeOptions = useReplayModeOptionsStore()
        const elapsedTime = await replayModeOptions.show(await agencyAsync.getFilteredSessionListTotalLength())
        if (elapsedTime != null) await agencyAsync.startReplay(false, elapsedTime, null)
        break
      case appoxEnums.ApplicationMode.Remote:
        const remoteModeOptions = useRemoteModeOptionsStore()
        const startPosixTime = await remoteModeOptions.show()
        if (startPosixTime != null) await agencyAsync.startRemote(false, true, null, startPosixTime)
        break
    }
  }
  
  async function startRecord() {
    switch (appMode.value) {
      case appoxEnums.ApplicationMode.Online:
        await agencyAsync.startOnline(false, false, null)
        break
      case appoxEnums.ApplicationMode.Offline:
        await agencyAsync.startOffline(false, false, null)
        break
      case appoxEnums.ApplicationMode.Remote:
        const remoteModeOptions = useRemoteModeOptionsStore()
        const startPosixTime = await remoteModeOptions.show()
        if (startPosixTime != null) await agencyAsync.startRemote(false, false, null, startPosixTime)
        break
    }
  }
  
  async function stop() {
    await agencyAsync.stopRunning(false, true)
  }
  
  async function setInterestTime(time) {
    lastSetTargetInterestTime = Date.now()
    interestTime.value = time
    await agencyAsync.setInterestTime(time)
  }
  
  async function setTargetReplaySpeed(speed) {
    lastSetTargetReplaySpeedTime = Date.now()
    targetReplaySpeed.value = speed
    await agencyAsync.setTargetReplaySpeed(speed)
  }
  
  async function sendManualTrigger(index) {
    await agencyAsync.sendManualTrigger(index)
  }

  // 更新所有状态
  async function updateMain() {
    if (updating) return
    updating = true

    try {
      const [
        status,
        mode,
        path,
        withRecording,
        actualSpeed,
        targetSpeed,
        switchSessionAvailable
      ] = await Promise.all([
        agencyAsync.getAppStatus(),
        agencyAsync.getAppMode(),
        agencyAsync.getGlobalParameter("System.DataPath", null),
        agencyAsync.isFileOutputEnabled(),
        agencyAsync.getSystemStatus(appoxEnums.SystemStatus.ActualReplaySpeed),
        agencyAsync.getSystemStatus(appoxEnums.SystemStatus.TargetReplaySpeed),
        agencyAsync.isSwitchSessionAvailable()
      ])
      
      // 更新基本状态
      appStatus.value = status
      
      // 检查模式切换的防抖
      if (lastSwitchAppModeTime == null || Date.now() - lastSwitchAppModeTime > 1000) {
        appMode.value = mode
      }
      
      dataPath.value = path == null || path == 'na' ? '---' : path
      isFileOutputEnabled.value = withRecording
      isSwitchSessionAvailable.value = switchSessionAvailable

      // 更新回放速度信息
      actualReplaySpeed.value = Number(actualSpeed)
      
      // 检查回放速度的防抖
      if (lastSetTargetReplaySpeedTime == null || Date.now() - lastSetTargetReplaySpeedTime > 1000) {
        targetReplaySpeed.value = Number(targetSpeed)
      }
    } finally {
      updating = false
    }
  }

  // 更新时间轴相关信息
  async function updateTimeline() {
    let interest = appoxUtility.getInterestTimeLocal()
    let bufferRange = appoxUtility.getBufferRangeLocal()
    
    // 更新缓冲区信息
    if (bufferRange) {
      bufferBegin.value = bufferRange.begin
      bufferEnd.value = bufferRange.end
    }
    
    // 检查兴趣点时间的防抖
    if (lastSetTargetInterestTime == null || Date.now() - lastSetTargetInterestTime > 1000) {
      interestTime.value = interest || 0
    }
  }

  // 更新所有状态
  function updateAll() {
    updateMain()
    updateTimeline()
  }

  // 更新控制器面板可用性
  async function updateControllerPanelAvailability() {
    isConfigDataPathAvailable.value = await agencyAsync.getConsoleClassInfo("config-data-path.consoleworkflow") != null
  }

  // 运行数据路径配置工作流
  async function runDataPathConfigWorkflow() {
    await agencyAsync.runConsole("config-data-path.consoleworkflow")
  }

  return {
    // 状态
    appStatus,
    appMode,
    dataPath,
    isConfigDataPathAvailable,
    isFileOutputEnabled,
    isSwitchSessionAvailable,
    bufferBegin,
    bufferEnd,
    interestTime,
    targetReplaySpeed,
    actualReplaySpeed,
    // 计算属性
    isIdle,
    isRunning,
    isDataPathValid,
    isDataSettingsConfigurable,
    isOnlineMode,
    isRemoteMode,
    isOfflineMode,
    isReplayMode,
    canAccessSessionList,
    canSelectDataPath,
    canAccessGenerationSetting,
    canRecord,
    canPreview,
    previewButtonType,
    recordButtonType,
    stopButtonType,
    showReplaySpeed,
    formatReplaySpeed,
    // 动作
    switchToOnlineMode,
    switchToRemoteMode,
    switchToOfflineMode,
    switchToReplayMode,
    startPreview,
    startRecord,
    stop,
    setInterestTime,
    setTargetReplaySpeed,
    sendManualTrigger,
    updateAll,
    updateControllerPanelAvailability,
    runDataPathConfigWorkflow
  }
}) 